package com.glsc.ngateway.platform.service.cmdb;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.api.common.enums.DictConstant;
import com.glsc.ngateway.common.base.domain.mysql.cmdb.CmdbChangeLog;
import com.glsc.ngateway.common.base.domain.mysql.cmdb.CmdbDeviceDetail;
import com.glsc.ngateway.common.base.domain.mysql.cmdb.CmdbPartDetail;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.flow.cmdb.FlowFormPartIn;
import com.glsc.ngateway.common.base.exception.PlatformException;
import com.glsc.ngateway.common.base.repo.mysql.cmdb.*;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.flow.cmdb.FlowFormPartInRepo;
import com.glsc.ngateway.platform.utils.SpecificationUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static com.glsc.ngateway.common.api.common.enums.DictConstant.*;

@Service
public class CmdbPartDetailService {

    @Autowired
    private SequenceProductService sequenceProductService;
    @Autowired
    private CmdbPartDetailRepository cmdbPartDetailRepository;
    @Autowired
    private CmdbChangeLogRepository cmdbChangeLogRepository;
    @Autowired
    private FlowFormPartInRepo flowFormPartInRepo;

    public Object search(String type, Object paramsObj) {
        JSONObject objParmams = JSONObject.parseObject(JSONObject.toJSONString(paramsObj)).entrySet().stream()
                .filter(entry -> !entry.getValue().toString().isEmpty())
                .collect(JSONObject::new, (obj, entry) -> obj.put(entry.getKey(), entry.getValue()), JSONObject::putAll);

        if (StrUtil.isEmpty(objParmams.getString("orderByDirection"))){
            objParmams.put("orderByDirection","DESC");
        }
        if (StrUtil.isEmpty(objParmams.getString("orderByField"))){
            objParmams.put("orderByField","id");
        }
        Sort sort = Sort.by(Sort.Direction.fromString(objParmams.getString("orderByDirection")), objParmams.getString("orderByField"));

        Pageable pageable = PageRequest.of(objParmams.getInteger("pageNo")- 1, objParmams.getInteger("pageSize"),sort);

        if (CMDB_PART_DETAIL.equals(type)){
            CmdbPartDetail paramSearchDto = JSONObject.parseObject(JSONObject.toJSONString(objParmams),CmdbPartDetail.class);
            Page<CmdbPartDetail> result = cmdbPartDetailRepository.searchByParam(pageable,paramSearchDto);
            result.getContent().forEach(e -> {
                if (e.getCmdbPartStandard() != null){
                    e.setPartNum(e.getCmdbPartStandard().getPartNum());
                }
            });
            return  result;
        }

        return null;
    }

    /**
     * @param cmdbPartDetail
     * @param account        操作人员
     * @param cmdbConfirm
     */
    public CmdbPartDetail addOrUpdatePartDetail(CmdbPartDetail cmdbPartDetail, String account, String cmdbConfirm) {
        int addOrUpdateFlag = 0;
        cmdbPartDetail.setIsDelete(NO_DELETE);
        CmdbChangeLog log = new CmdbChangeLog();
        if (cmdbPartDetail.getPartDetailId() != null){
            //修改
            log.setChangeType(DictConstant.UPDATE_STRING);
            addOrUpdateFlag = 2;
        } else {
            //新增
            log.setChangeType(DictConstant.ADD_STRING);
            //自动生成编号
            String code = sequenceProductService.buildSequence(CMDB_PART_DETAIL);
            cmdbPartDetail.setPartDetailCode(code);
            addOrUpdateFlag = 1;
        }
        if (addOrUpdateFlag != 0){
            checkUnique(cmdbPartDetail,addOrUpdateFlag,cmdbConfirm);
        }
        log.setChangeContent(JSONObject.toJSONString(cmdbPartDetail));
        log.setChangeFrom(CMDB_PART_DETAIL);
        log.setChangeId(cmdbPartDetail.getPartDetailId() != null ? cmdbPartDetail.getPartDetailId().toString() : null);
        log.setChangeUser(account);
        cmdbChangeLogRepository.save(log);
        cmdbPartDetailRepository.save(cmdbPartDetail);
        return cmdbPartDetail;
    }

    private void checkUnique(CmdbPartDetail cmdbPartDetail, int addOrUpdateFlag, String cmdbConfirm) {
        if (StrUtil.isNotEmpty(cmdbPartDetail.getSn())){
            if (addOrUpdateFlag == 1){
                findSame(cmdbPartDetail,cmdbConfirm);
            } else {
                //修改情况，要把已有结果查询出来，如果有变化还要校验
                Optional<CmdbPartDetail> result = cmdbPartDetailRepository.findById(cmdbPartDetail.getPartDetailId());
                if (result.isPresent()){
                    if (result.get().getSn() != null && ! result.get().getSn().equals(cmdbPartDetail.getSn())){
                        if (result.get().getIsDelete().equals(NO_DELETE)){
                            findSame(cmdbPartDetail,cmdbConfirm);
                        }
                    }
                    //修改情况存在未删除的记录
                } else {
                    findSame(cmdbPartDetail,cmdbConfirm);
                }
            }

        }
    }

    public void findSame(CmdbPartDetail cmdbPartDetail, String cmdbConfirm) {
        List<CmdbPartDetail> result = cmdbPartDetailRepository.findAllBySnAndIsDelete(cmdbPartDetail.getSn(), NO_DELETE);
        if (CollectionUtil.isNotEmpty(result)){
            throw PlatformException.errorWithOutMail("序列号重复");
        }
        if (!StrUtil.equals(CMDB_CONFIRM,cmdbConfirm)){
            List<FlowFormPartIn> flowFormPartInDetails = flowFormPartInRepo.findFlowPartSn(cmdbPartDetail.getSn());
            if (CollectionUtil.isNotEmpty(flowFormPartInDetails)){
                throw PlatformException.errorWithOutMail("有发起过的流程"+flowFormPartInDetails.get(0).getProcessTitle()+"存在相同的配件序列号");
            }
        }
    }

    public void deletePartDetail(CmdbPartDetail cmdbPartDetail, String account) {
        CmdbChangeLog log = new CmdbChangeLog();
        log.setChangeContent(JSONObject.toJSONString(cmdbPartDetail));
        log.setChangeFrom(CMDB_PART_DETAIL);
        log.setChangeId(cmdbPartDetail.getPartDetailId().toString());
        log.setChangeUser(account);
        log.setChangeType(DELETE_STRING);
        Optional<CmdbPartDetail> optional = cmdbPartDetailRepository.findById(cmdbPartDetail.getPartDetailId().intValue());
        if (optional.isPresent()) {
            CmdbPartDetail bean = optional.get();
            bean.setIsDelete(DELETED);
            cmdbPartDetailRepository.save(bean);
            cmdbChangeLogRepository.save(log);
        } else {
            throw PlatformException.errorWithOutMail("删除记录不存在");
        }
    }

    public void deleteByCodeList(List<String> codes, String account) {
        CmdbChangeLog log = new CmdbChangeLog();
        log.setChangeContent(JSONObject.toJSONString(codes));
        log.setChangeFrom(CMDB_PART_DETAIL);
        log.setChangeUser(account);
        log.setChangeType(DELETE_BATCH_STRING);
        cmdbChangeLogRepository.save(log);
        cmdbPartDetailRepository.updateIsDeleteByCodes(DELETED,codes);
    }

    public void deleteByDeviceDetailId(Integer deviceDetailId, String operator) {
        CmdbChangeLog log = new CmdbChangeLog();
        log.setChangeContent(JSONObject.toJSONString(deviceDetailId));
        log.setChangeFrom(CMDB_DEVICE_DETAIL);
        log.setChangeUser(operator);
        log.setChangeType(DELETE_BATCH_STRING);
        cmdbChangeLogRepository.save(log);
        cmdbPartDetailRepository.updateIsDeleteByDeviceDetailId(DELETED, deviceDetailId);
    }

    public void outByDeviceDetail(CmdbDeviceDetail h, String operator) {
        List<CmdbPartDetail> partDetails = cmdbPartDetailRepository.findAllByDeviceCodeAndIsDelete(h.getDeviceDetailCode(), NO_DELETED);
        partDetails.stream().forEach(e -> e.setLifeStatus(PART_LIFE_CYCLE_OUT));
        cmdbPartDetailRepository.saveAll(partDetails);
        CmdbChangeLog log = new CmdbChangeLog();
        log.setChangeContent(JSONObject.toJSONString(h.getDeviceDetailId()));
        log.setChangeFrom(CMDB_DEVICE_DETAIL);
        log.setChangeUser(operator);
        log.setChangeType(UPDATE_STRING);
        cmdbChangeLogRepository.save(log);
    }

    public void outBySn(String sn, String operator) {
        List<CmdbPartDetail> partDetails = cmdbPartDetailRepository.findAllBySnAndIsDelete(sn, NO_DELETED);
        CmdbPartDetail partDetail = partDetails.get(0);
        partDetail.setLifeStatus(PART_LIFE_CYCLE_OUT);
        cmdbPartDetailRepository.save(partDetail);
        CmdbChangeLog log = new CmdbChangeLog();
        log.setChangeContent(JSONObject.toJSONString(sn));
        log.setChangeFrom(CMDB_MEMORY_DETAIL);
        log.setChangeUser(operator);
        log.setChangeType(UPDATE_STRING);
        cmdbChangeLogRepository.save(log);
    }

    /**
     * 根据序列号查询
     *
     * @param snList
     * @return
     */
    public List<CmdbPartDetail> listBySn(List<String> snList) {
        Map<String, Object> param = new HashMap<>();
        param.put("INSTR_sn", StringUtils.join(snList,","));
        param.put("EQ_isDelete", 0);

        List<CmdbPartDetail> detailLis = cmdbPartDetailRepository.findAll(SpecificationUtil.buildSpecification(param, CmdbPartDetail.class));
        return detailLis;
    }

    public List<CmdbPartDetail> listByDetailCode(List<String> collect) {
        return cmdbPartDetailRepository.findAllByPartDetailCodeIn(collect);
    }
}


